﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FoundationLib.Ifc.Authorisation.Configuration;
using System.Diagnostics.Contracts;

namespace FoundationLib.Ifc.Authorisation
{
	/// <summary>
	/// This class manages authorisation services.
	/// </summary>
	public static class AuthorisationManager
	{
		/// <summary>
		/// The configuration
		/// </summary>
		private static AuthorisationConfigSection configuration;

		/// <summary>
		/// Ensures that the configuration has been loaded.
		/// </summary>
		private static void AssertConfigLoaded()
		{
			if (configuration == null)
				configuration = AuthorisationConfigSection.FromConfiguration();
		}

		/// <summary>
		/// Returns a <see cref="IAuthorisationService"/> instance for the service with the specified name.
		/// </summary>
		/// <param name="name">The service name</param>
		/// <returns>The instance or null on error</returns>
		public static IAuthorisationService ServiceFor(string name)
		{
			Contract.Requires(!String.IsNullOrWhiteSpace(name), "A service name must be provided.");

			AssertConfigLoaded();
			AuthorisationConfigElement element = configuration.Services[name];
			Contract.Assert(element != null, String.Format("A service for '{0}' was not found in the configuration.", name));

			Type type = Type.GetType(element.Implementation, true);
			IAuthorisationService instance = Activator.CreateInstance(type) as IAuthorisationService;
			if (instance != null)
				instance.Configuration = element;
			return instance;
		}
	}
}
